package com.e.library.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by e on 2017/10/16.
 */

public final class EStack {

    private static List<Activity> activities = new ArrayList<Activity>();

    public static void onResume(Activity activity){
        if(!activities.contains(activity)){
            activities.add(0,activity);
        }
    }

    public static void onStop(Activity activity){
        activities.remove(activity);
    }

    public static boolean isEmpty(){
        return activities.isEmpty();
    }

    public static void onBackPressed(Activity activity){
        if(activities.isEmpty()) {
            toMainActivity(activity);
            return;
        }
        if(!hasMainActivity()) {
            /**表示从推送打开的页面*/
            toMainActivity(activity);
        }
    }

    private static boolean hasMainActivity(){
        boolean match = false;
        for (Activity a:activities){
            if("com.wedo.mall.activity.MainActivity".equals(a.getClass().getName())) {
                match = true;
                break;
            }
        }
        return match;
    }

    private static void toMainActivity(Activity activity){
        try {
            Intent intent = new Intent();
            intent.setClassName(activity,"com.wedo.mall.activity.MainActivity");
            activity.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void onBackPressed(Context context,String activityName){
        if(activities.isEmpty()) {
            toActivity(context,activityName);
            return;
        }
        if(!hasActivity(activityName)) {
            /**表示从推送打开的页面*/
            toActivity(context,activityName);
        }
    }

    private static boolean hasActivity(String activityName){
        boolean match = false;
        for (Activity a:activities){
            if(activityName.equalsIgnoreCase(a.getClass().getName())) {
                match = true;
                break;
            }
        }
        return match;
    }

    private static void toActivity(Context context,String activityName){
        try {
            Intent intent = new Intent();
            intent.setClassName(context,activityName);
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
